package com.nsqt.biz.controller;

import com.nsqt.biz.domain.AgentDO;
import com.nsqt.biz.domain.InfocollDO;
import com.nsqt.biz.domain.SoftwareDO;
import com.nsqt.biz.service.AgentService;
import com.nsqt.biz.service.InfocollService;
import com.nsqt.biz.service.SoftwareService;
import com.nsqt.common.utils.*;
import com.nsqt.system.domain.UserDO;
import com.nsqt.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 软著信息采集
 */
@Controller
@RequestMapping("/biz/infocoll")
public class InfocollController {
    @Autowired
    private InfocollService infocollService;
    @Autowired
    private UserService userService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private SoftwareService softwareService;

    @GetMapping()
    String Infocoll() {
        return "biz/infocoll/infocoll";
    }

    @ResponseBody
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        Long currUserId = ShiroUtils.getUserId();
        query.put("businessMan", currUserId);

        List<InfocollDO> infocollList = infocollService.list(query);
        int total = infocollService.count(query);
        PageUtils pageUtils = new PageUtils(infocollList, total);
        return pageUtils;
    }

    /**
     * 简易采集软著信息
     */
    @GetMapping("/simcoll")
    String simcoll(HttpServletRequest request, Model model) {
        String seckey = request.getParameter("seckey");
        if (seckey == null || seckey == "") {
            return "404";
        }
        String userId = "";
        String agentId = "";

        List<UserDO> userList = userService.list(new HashMap<>());
        for (UserDO user : userList
        ) {
            System.out.println(user.getUserId().toString() + ": ");

            System.out.println(MD5Utils.encrypt(user.getUserId().toString()) + ": ");

            System.out.println(seckey.substring(0, 32) + " + ");

            System.out.println(seckey.substring(32, 64));
            if (MD5Utils.encrypt(user.getUserId().toString()).equals(seckey.substring(0, 32))) {
                userId = user.getUserId().toString();
                break;
            }
        }

        List<AgentDO> agentList = agentService.list(new HashMap<>());
        for (AgentDO agent : agentList
        ) {
            if (MD5Utils.encrypt(agent.getId().toString()).equals(seckey.substring(32, 64))) {
                agentId = agent.getId().toString();
                break;
            }
        }
        if (userId == "" || agentId == "") {
            return "404";
        }
        model.addAttribute("userId", userId);
        model.addAttribute("agentId", agentId);
        return "biz/infocoll/simcoll";

    }

    /**
     * 新增软著信息采集
     */
    @GetMapping("/add")
    String add(HttpServletRequest request, Model model) {
        String seckey = request.getParameter("seckey");


        Map map = new HashMap();
        map.put("status", 1);
        map.put("liveAddress", seckey);
        List<UserDO> list = userService.list(map);
        if (list.size() > 0) {
            UserDO userDO = list.get(0);
            model.addAttribute("userDO", userDO);
            return "biz/infocoll/add";
        }
        return "404";
    }

    /**
     * 编辑软著信息采集
     */
    @GetMapping("/edit/{id}")
    String edit(@PathVariable("id") Integer id, Model model) {
        InfocollDO infocoll = infocollService.get(id);
        model.addAttribute("infocoll", infocoll);
        return "biz/infocoll/edit";
    }


    /**
     * 保存内部人员提交的软著信息采集
     */
    @ResponseBody
    @PostMapping("/save")
    public R save(InfocollDO infocoll) {
        if (infocollService.save(infocoll) > 0) {

            return R.ok();
        }
        return R.error();
    }

    /**
     * 保存客户提交的软著信息采集
     */
    @ResponseBody
    @PostMapping("/csave")
    public R cstmSave(InfocollDO infocoll) {

        if (infocollService.save(infocoll) > 0) {
            SoftwareDO software = new SoftwareDO();
            software.setSn("");
            software.setStatus(0);
            software.setCopyrightOwner(infocoll.getCopyrightOwner());
            software.setSoftwareName(infocoll.getSoftwareName());
            software.setBusinessMan(infocoll.getBusinessMan());

            softwareService.save(software);
            return R.ok();
        }
        return R.error();
    }

    /**
     * 简单采集客户提交的软著信息采集
     */
    @ResponseBody
    @PostMapping("/simsave")
    public R simsave(HttpServletRequest request) {
        String copyrightOwners[] = request.getParameterValues("copyrightOwner");
        String certNos[] = request.getParameterValues("certNo");
        String softNames[] = request.getParameterValues("softwareName");
        String softCompltdates[] = request.getParameterValues("softCompltdate");
        String publishDates[] = request.getParameterValues("publishDate");
        String ownerCity = request.getParameter("ownerCity");
        String companyOpdate = request.getParameter("companyOpdate");
        if (companyOpdate == null || companyOpdate.equals("")) {
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
            companyOpdate = format2.format(Calendar.getInstance().getTime());
        }
        String contact = request.getParameter("contact");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        Integer workDays = Integer.valueOf(request.getParameter("workDays"));
        Integer businessMan = Integer.valueOf(request.getParameter("businessMan"));
        Long agentId = Long.valueOf(request.getParameter("agentId"));
        String copyrightOwner = "";
        String idType = "";
        if (copyrightOwners[0].length() > 6) {
            idType = "居民身份证";
        } else {
            idType = "企业法人";
        }
        int copyAmount = copyrightOwners.length - 1;
        if (copyAmount == 0) {
            copyrightOwner = copyrightOwners[0];
        } else {
            for (int i = 0; i < copyrightOwners.length; i++) {
                if (!copyrightOwners[i].equals("")) {
                    copyrightOwner += copyrightOwners[i] + ";\n";
                }
            }
        }
        String certNo = "";
        if (copyAmount == 0) {
            certNo = certNos[0];
        } else {
            for (int i = 0; i < certNos.length; i++) {
                if (!certNos[i].equals("")) {
                    certNo += certNos[i] + ";\n";
                }
            }
        }

        for (int i = 0; i < softNames.length; i++) {
            if (softNames[i].equals("")) {
                continue;
            }
            InfocollDO infocoll = new InfocollDO(copyrightOwner, certNo, companyOpdate, contact, phone, address,
                    idType, softNames[i], softCompltdates[i], publishDates[i]);
            infocoll.setBusinessMan(businessMan);
            infocoll.setAgent(agentId);
            infocoll.setOwnerCity(ownerCity);
            infocoll.setPublishCity(ownerCity);
            infocoll.setCopyAmount(copyAmount);
            infocoll.setStatus(0);//status: 0,
            infocoll.setWorkDays(workDays);
            infocollService.save(infocoll);

        }

        return R.ok();
    }

    /**
     * 修改软著信息采集
     */
    @ResponseBody
    @RequestMapping("/update")
    public R update(InfocollDO infocoll) {
        infocollService.update(infocoll);
        return R.ok();
    }

    /**
     * 删除软著信息采集
     */
    @PostMapping("/remove")
    @ResponseBody
    public R remove(Integer id) {
        if (infocollService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * get union code
     */
    @PostMapping("/getUnionCode")
    @ResponseBody
    public R getUnionCode(String copyrightOwner) {
        InfocollDO info = infocollService.getByCopyrightOwner(copyrightOwner);
        String unionCode = "";
        if (info != null) {
            unionCode = info.getCertNo();
        }
        return R.ok(unionCode);
    }

    /**
     * 批量删除软著信息采集
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        infocollService.batchRemove(ids);
        return R.ok();
    }


    /**
     * 批量填报软著信息
     */
    @PostMapping("/batchCommit")
    @ResponseBody
    public R batchCommit(@RequestParam("ids[]") Integer[] ids) {

        infocollService.batchCommit(ids);
        return R.ok();
    }
}
